package timesheet.repository;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import timesheet.model.Event;
import timesheet.model.Project;
import timesheet.model.Users;

@Repository
@SuppressWarnings("unchecked")
public class EventRepository {
	@PersistenceContext
    EntityManager em;
	
	
	public void createEvent(Event e) {
		em.persist(e);
	}
	
	
	public void merge(Event e) {
		em.merge(e);
	}
	
	public void detacheEntity(Event e) {
		em.detach(e);
	}
	
	public void remove(Event e) {
		em.remove(e);
	}
	
	public Event find(Long id){
		return em.find(Event.class, id);
	}
	
	
	public List<Event> getAllEvent() {
        List<Event> EventList = em.createQuery("select e from Event e")
         .getResultList();
    return EventList;     
	}
	
//	public List<Event> getUserEvent(Long section){
//		String user = String.valueOf(section);
//		List<Event> EventList = em.createQuery("select e from Event e where e.sectionId = :user ORDER BY e.startTime")
//				  				  .setParameter("user", user)
//				  				  .getResultList();
//		return EventList;   
//	}
	
	public List<Event> getAllEventByDate(Date from, Date to, String condition, String projectCondition){
		List <Event> list = em.createQuery("select e from Event e where e.startTime >= :from and e.startTime <= :to and e.statut = \'1\' "+condition+" "+projectCondition+ "ORDER BY e.u.id").setParameter("from", from).setParameter("to", to).getResultList();
		return list;
	}
	
	public List<Event> getAllEventByproject(Project p){
		List <Event> list = em.createQuery("select e from Event e where e.p = :p").setParameter("p", p).getResultList();
		return list;
	}
	
	public List<Event> getAllEventByUser(Users u){
		List <Event> list = em.createQuery("select e from Event e where e.u = :u").setParameter("u", u).getResultList();
		return list;
	}
	
	public List<Event> getAllEventByUserOrProjectList(String condition){
		List <Event> list = em.createQuery("select e from Event e "+condition).getResultList();
		return list;
	}
	
	protected Event getSingleOrNullResult(Query query) {
        try {
            Event result = (Event)query.getSingleResult();
            return result;
        } catch (NoResultException nre) {
            return null;  // Normal, entity is just not found.
        }
    }
}
